package a66weding.com.jiehuntong.activity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.adapter.CommonAdapter;
import a66weding.com.jiehuntong.adapter.MyFancyCoverFlowAdapter;
import a66weding.com.jiehuntong.adapter.ViewHolder;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SimpleBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.ThemeSettingsInfo;
import a66weding.com.jiehuntong.beans.ThemeStyles;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import at.technikum.mti.fancycoverflow.FancyCoverFlow;

import static a66weding.com.jiehuntong.activity.ElectronicInvitationActivity.ACTION_REFRESH_INVITATION;

/**
 * 主题设置界面
 */
public class ThemeSettingsActivity extends BaseHomeActivity implements View.OnClickListener, OnNetResultListener {
    private FancyCoverFlow mFancyCoverFlow;
    private Button tv_use_theme;
    private ArrayList<String> imgUrls = new ArrayList<>();
    private TextView tv_current_music_name;
    private TextView tv_contact_us;
    private boolean isShowPhone = false;
    private String currentMusicName = "";
    private MyFancyCoverFlowAdapter mFancyCoverFlowAdapter;
    private Intent intent;
    private int musicIndex;
    private String nvcMusicCustom;//自定义音乐网络地址
    private GridView popGrideView;
    private PopupWindow popupWindow;
    private ThemeStyles themeStyles;
    private int currentThemeID;//当前显示的主题id
    private int currentThemeType;//当前显示的主题类型
    private List<ThemeStyles.DataBean> styleData;
    private int useId;//当前使用的id
    private int netRequestID;//记录准备网络设置的id
    private LinearLayout llayHave;
    private ImageView imgNone;
    /**
     * 广播用来更新预览设置
     */
    public static final String ACTION_REFRESH_PREVIEWINVITATION = "a66weding.com.jiehuntong.previewinvitation";
//    public static final String ACTION__FINISH_ACTIVITY = "a66weding.com.jiehuntong.themesettingsactivity";
    //  private int PREVIEW=123;
    private int previewID;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_theme_settings);
        //获得传递过来的当前音乐主题,是否开启了联系人显示
        currentMusicName = getIntent().getStringExtra("musicname");
        isShowPhone = getIntent().getBooleanExtra("isShow", false);
        musicIndex = getIntent().getIntExtra("musicIndex", 0);
        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_REFRESH_PREVIEWINVITATION);
        registerReceiver(myReceiver, filter);
        initView();
        inintPOP();
        initeDate();
    }

    @Override
    protected void onDestroy() {
        //取消注册的广播
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }
    private void inintPOP() {
        View view = this.getLayoutInflater().inflate(R.layout.pop_theme_style, null);
        view.findViewById(R.id.pop_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    viewBootomLine.setBackgroundColor(getResources().getColor(R.color.colortheme));
                }
            }
        });
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popGrideView = (GridView) view.findViewById(R.id.pop_gv_styles);
        popGrideView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                setGralley(position);
                ListAdapter adapter = popGrideView.getAdapter();
                ThemeStyles.DataBean typeItem = (ThemeStyles.DataBean) adapter.getItem(position);
                currentThemeType = typeItem.getI_id();
                setGralley(currentThemeType);//设置当前需要显示的图画廊
                tvNavRightText.setText(typeItem.getNvc_Name());
                //修改按钮颜色
                if (adapter != null && popGrideView.getCount() > 0) {
                    for (int i = 0; i < adapter.getCount(); i++) {
                        LinearLayout item = (LinearLayout) popGrideView.getChildAt(i);
                        TextView childAt = (TextView) item.getChildAt(0);
                        if (position == i) {
                            childAt.setSelected(true);
                        } else {
                            childAt.setSelected(false);
                        }
                    }
                }
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    viewBootomLine.setBackgroundColor(getResources().getColor(R.color.colortheme));
                }
            }
        });
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.color.push_translucent);
        BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
        popupWindow.setBackgroundDrawable(bitmapDrawable);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setContentView(view);
    }

    private void initeDate() {
        int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        HttpRequestBean httpRequestBean = new HttpRequestBean();
        //当前设置请求
        httpRequestBean.setListener(this);
        httpRequestBean.setClazz(ThemeSettingsInfo.class);
        httpRequestBean.setRequestMethod(RequestCode.GETREQUEST);
        httpRequestBean.setUrl(RequestCode.SURL + RequestCode.CURRENTINVITESETTINGS + uId);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
        //模板风格
        httpRequestBean.setListener(this);
        httpRequestBean.setClazz(ThemeStyles.class);
        httpRequestBean.setRequestMethod(RequestCode.GETREQUEST);
        httpRequestBean.setUrl(RequestCode.SURL + RequestCode.THEMESTYLES);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }

    //头部导航条
    private LinearLayout llNavRoot;
    private RelativeLayout rlayNavContains;
    private LinearLayout llayNavLeft;
    private ImageView imgNavBack;
    private TextView tvNavLefttext;
    private LinearLayout llayNavRight;
    private TextView tvNavRightText;
    private TextView tvNavCenterText;
    private View viewBootomLine;

    @TargetApi(Build.VERSION_CODES.M)
    private void initView() {
        RelativeLayout rl_contact_us = (RelativeLayout) findViewById(R.id.rl_contact_us);
        tv_use_theme = (Button) findViewById(R.id.tv_use_theme);
        tv_use_theme.setOnClickListener(this);
        tv_use_theme.setSelected(true);
        tv_use_theme.setText("当前主题");
        tv_current_music_name = (TextView) findViewById(R.id.tv_current_music_name);
        tv_current_music_name.setText(currentMusicName);
        tv_contact_us = (TextView) findViewById(R.id.tv_contact_us);
        imgNone = (ImageView) findViewById(R.id.img_none);
        llayHave = (LinearLayout) findViewById(R.id.llay_have);
        imgNone.setVisibility(View.VISIBLE);
        llayHave.setVisibility(View.GONE);
        RelativeLayout rl_theme_music = (RelativeLayout) findViewById(R.id.rl_theme_music);
        rl_contact_us.setOnClickListener(this);
        rl_theme_music.setOnClickListener(this);

        mFancyCoverFlow = (FancyCoverFlow) findViewById(R.id.mFancyCoverFlow);
        mFancyCoverFlow.setUnselectedSaturation(1.0f);
        mFancyCoverFlow.setUnselectedAlpha(1);//设置透明度
        mFancyCoverFlow.setUnselectedScale(0.83f);//为被选中的缩放比
        mFancyCoverFlow.setSpacing(Utils.dip2px(this, 29f));//两个图形的距离
        mFancyCoverFlow.setMaxRotation(0);//设置最大旋转角度
        mFancyCoverFlow.setScaleDownGravity(0.5f);//图片下沉度数
        //监听条目滑动改变
        mFancyCoverFlow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ThemeStyles.DataBean.TemplateListBean templateListBean = (ThemeStyles.DataBean.TemplateListBean) mFancyCoverFlow.getAdapter().getItem(position);
                currentThemeType = templateListBean.getI_Type();
                currentThemeID = templateListBean.getI_id();
                if (useId == templateListBean.getI_id()) {
                    tv_use_theme.setSelected(true);
                    tv_use_theme.setText("当前主题");
                    //tv_use_theme.setEnabled(false);
                } else {
                    tv_use_theme.setText("使用此主题");
                    tv_use_theme.setSelected(false);
                    //tv_use_theme.setEnabled(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //点击进行预览主题
        mFancyCoverFlow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ThemeSettingsActivity.this, PreviewThemeActivity.class);
                ThemeStyles.DataBean.TemplateListBean item = mFancyCoverFlowAdapter.getItem(position);
                previewID = item.getI_id();
                intent.putExtra("TempUrl", item.getTempUrl());
                intent.putExtra("tid", item.getI_id());
                intent.putExtra("useId", useId);
//                startActivityForResult(intent,PREVIEW);
                startActivity(intent);
            }
        });


        //头部导航条
        llNavRoot = (LinearLayout) findViewById(R.id.ll_nav_root);
        rlayNavContains = (RelativeLayout) findViewById(R.id.rlay_nav_contains);
        llayNavLeft = (LinearLayout) findViewById(R.id.llay_nav_left);
        imgNavBack = (ImageView) findViewById(R.id.img_nav_back);
        tvNavLefttext = (TextView) findViewById(R.id.tv_nav_lefttext);
        llayNavRight = (LinearLayout) findViewById(R.id.llay_nav_right);
        tvNavRightText = (TextView) findViewById(R.id.tv_nav_righttext);
        tvNavCenterText = (TextView) findViewById(R.id.tv_nav_center_text);
        viewBootomLine = (View) findViewById(R.id.view_bootom_line);
        viewBootomLine.setBackgroundColor(getResources().getColor(R.color.colortheme));
        rlayNavContains.setBackgroundColor(getResources().getColor(R.color.colortheme));
        tvNavCenterText.setText("主题设置");
        tvNavRightText.setText("");
        tvNavLefttext.setText(null);
        llayNavLeft.setOnClickListener(this);
        llayNavRight.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_nav_left:
                finish();
                break;
            case R.id.llay_nav_right:
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    viewBootomLine.setBackgroundColor(getResources().getColor(R.color.colortheme));
                } else if (popupWindow != null && !popupWindow.isShowing()) {
                    viewBootomLine.setBackgroundColor(getResources().getColor(R.color.color_nav_theme));
                    popupWindow.showAsDropDown(viewBootomLine, Gravity.BOTTOM, Gravity.CENTER_HORIZONTAL);//设置在屏幕中的显示位置
                }
                break;
            case R.id.rl_contact_us:
                intent = new Intent(this, ContactUsActivity.class);
                intent.putExtra("isShow", isShowPhone);
                startActivityForResult(intent, 99);
                break;
            case R.id.rl_theme_music:
                intent = new Intent(this, ThemeMusicActivity.class);
                intent.putExtra("nvcMusicCustom", nvcMusicCustom);
                intent.putExtra("currentMusicName", currentMusicName);
                intent.putExtra("musicIndex", musicIndex);
                    startActivityForResult(intent, 69);
               // startActivity(intent);
                break;
            case R.id.tv_use_theme:
                if (useId != currentThemeID) {
                    //tv_use_theme.setEnabled(false);
                    netRequestID = currentThemeID;
                    int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
                    HttpRequestBean httpRequestBean = new HttpRequestBean();
                    // 设置使用模板
                    httpRequestBean.setListener(this);
                    httpRequestBean.setClazz(SimpleBean.class);
                    httpRequestBean.setRequestMethod(RequestCode.POSTEQUEST);
                    httpRequestBean.setUrl(RequestCode.SURL + RequestCode.UPMARRYCARDTEMPLATE + "&uid=" + uId + "&tid=" + netRequestID);
                    httpRequestBean.setRequestCode("setTheme");
                    HttpHandleUtil.executeCommonPost(this, httpRequestBean);
                }else {
                    //返回我的请柬
                    Intent intent =new Intent(this,ElectronicInvitationActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99) {
            if (data != null) {
                isShowPhone = data.getBooleanExtra("isShow", false);
                if (isShowPhone) {
                    tv_contact_us.setText("已启用");
                } else {
                    tv_contact_us.setText("未启用");
                }
            }
        } else if (requestCode == 69) {
            if (data != null) {
                String extra = data.getStringExtra("musicname");
                tv_current_music_name.setText(extra);//获取已经设置的音乐名字到当前
                musicIndex = data.getIntExtra("musicid", 0);//获取已经设置的音乐id避免再次进入还是老版的id导致显示bug
                finish();
            }

        }/*else if (requestCode==PREVIEW&&resultCode==RESULT_OK){//这里一定要判断resultCode不然从预览过后跳转到了主页面在返回isSeted会是空指针,因为主页面没设置任何的
            boolean isSeted = data.getBooleanExtra("isSeted",false);
            if (isSeted){
                useId=previewID;
                if (currentThemeID==useId){
                    tv_use_theme.setEnabled(false);
                    tv_use_theme.setSelected(true);

                }
            }
        }*/
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof ThemeSettingsInfo) {//页面当前使用的设置
            ThemeSettingsInfo response = (ThemeSettingsInfo) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    //用户使用的
                    useId = response.getData().getI_Tid();
                    musicIndex = response.getData().getI_MId();
                    isShowPhone = response.getData().isB_is_PhoneShow();
                    currentMusicName = response.getData().getNvc_MusicName();
                    nvcMusicCustom = response.getData().getNvc_MusicCustom();
                    tv_current_music_name.setText(currentMusicName);
                    if (isShowPhone) {
                        tv_contact_us.setText("已启用");
                    } else {
                        tv_contact_us.setText("未启用");
                    }
                } else {
                    CUtils.showToast(response.getMsg());
                }
            }
        } else if (data instanceof SimpleBean) {
            SimpleBean spb = (SimpleBean) data;
            if (spb != null && spb.getResCode() != null) {
                if (spb.getResCode().equals("0000")) {
                    CUtils.showToast("设置成功");
                    if (currentThemeID == netRequestID) {
                        tv_use_theme.setText("当前主题");
                        tv_use_theme.setSelected(true);
                       // tv_use_theme.setEnabled(false);
                    }
                    useId = netRequestID;
                    //请柬内容有修改后调用该行代码进行广播通知刷新数据
                    sendBroadcast(new Intent(ACTION_REFRESH_INVITATION));
                    //主题修改成功后返回我的请柬
                    Intent intent =new Intent(this,ElectronicInvitationActivity.class);
                    startActivity(intent);
                } else {
                    CUtils.showToast(spb.getMsg());
                }
            }
        } else if (data instanceof ThemeStyles) {
            themeStyles = (ThemeStyles) data;
            if (themeStyles != null && themeStyles.getResCode() != null) {
                if (themeStyles.getResCode().equals("0000")) {
                    styleData = themeStyles.getData();//所有需要使用到数据
                    setDate2popGride();//设置popwindow的界面
                    //设置当前页面选中的类型
                    boolean isBreak = false;
                    for (ThemeStyles.DataBean td : styleData) {
                        List<ThemeStyles.DataBean.TemplateListBean> templateList = td.getTemplateList();
                        for (ThemeStyles.DataBean.TemplateListBean tdtb : templateList) {
                            if (tdtb.getI_id() == useId) {
                                currentThemeType=tdtb.getI_Type();
                                isBreak = true;//跳出下个for循环
                                break;//跳出本for循环
                            }
                        }
                        if (isBreak){
                            tvNavRightText.setText(td.getNvc_Name());
                            break;
                        }
                    }
                    //页面的数据
                    setGralley(currentThemeType);
                } else {
                    CUtils.showToast(themeStyles.getMsg());
                }
            }
        }
    }

    private void setGralley(int type) {//设置显示的图片根据风格类型
        for (ThemeStyles.DataBean tll : styleData) {
            if (tll.getI_id() == type) {
                List<ThemeStyles.DataBean.TemplateListBean> templateList = tll.getTemplateList();
                if (templateList.size() > 0) {
                    mFancyCoverFlowAdapter = new MyFancyCoverFlowAdapter(templateList, ThemeSettingsActivity.this);
                    mFancyCoverFlow.setAdapter(mFancyCoverFlowAdapter);
                            //滑动到默认主题
                        for (int i=0;i<templateList.size();i++){
                            ThemeStyles.DataBean.TemplateListBean templateListBean = templateList.get(i);
                            if (templateListBean.getI_id()==useId){
                                mFancyCoverFlow.setSelection(i);
                                break;
                            }
                        }
                    imgNone.setVisibility(View.GONE);
                    llayHave.setVisibility(View.VISIBLE);
                } else {
                    imgNone.setVisibility(View.VISIBLE);
                    llayHave.setVisibility(View.GONE);
                }
                break;
            }
        }
    }

    private void setDate2popGride() {
        CommonAdapter<ThemeStyles.DataBean> commonAdapter = new CommonAdapter<ThemeStyles.DataBean>(this, styleData, R.layout.itme_styles) {
            @Override
            public void convert(ViewHolder holder, ThemeStyles.DataBean dataBean) {
                int i_id = dataBean.getI_id();
                TextView btnStyle = holder.getView(R.id.btn_style);
                btnStyle.setText(dataBean.getNvc_Name());
                if (currentThemeType == i_id) {
                    btnStyle.setSelected(true);
                }
            }
        };
        popGrideView.setAdapter(commonAdapter);
    }

    @Override
    public void onError(ErrorBean errorBean) {
        if (!TextUtils.isEmpty(errorBean.getRequestCode()) && errorBean.getRequestCode().equals("setTheme")) {
            CUtils.showToast("主题设置失败,请重新设置");
            //tv_use_theme.setEnabled(true);
        } else {
            CUtils.showToast("数据请求失败");
        }

    }

    //广播用来在预览设置后的更新
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_REFRESH_PREVIEWINVITATION)){
                //当预览后页面设置后在这里更新
                int previewID = intent.getIntExtra("previewID", -2);
                useId = previewID;
                if (currentThemeID == useId) {
                   // tv_use_theme.setEnabled(false);
                    tv_use_theme.setSelected(true);
                    tv_use_theme.setText("当前主题");
                }
            }/*else if (intent.getAction().equals(ACTION__FINISH_ACTIVITY)){
                Log.i("", "onReceive:收到广播关闭页面 ");
                finish();
            }*/
        }
    };

}

